<?php

namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Agent;
use app\common\model\Message;
use app\common\model\MoneyRecord;
use app\common\model\Recharge;
use app\common\model\Shop;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Queue;

class RechargeLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model = new Recharge();
    }


    /**
     * 搜索条件处理
     * @param Query $query
     * @param array $params
     * @return Query
     */
    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['date']) && !empty($params['date'])) {
            $date = explode('-',$params['date']);
            $date_arr = mFristAndLast($date[0],$date[1]);
            $query->whereBetween('createtime', [$date_arr['firstday'],$date_arr['lastday']]);
        }
        if (isset($params['shop_id']) && !empty($params['shop_id'])){
            $query->where('shop_id', $params['shop_id']);
        }
        return $query;
    }

    /**
     * 商家充值记录列表
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        $list = $this->getPageList($params)->each(function (&$item){
            $arr = [];
            $item['time'] = '暂无';
            if ($item['status'] == 1) //代理已充值
            {
                $item['time'] = empty($item['agenttime']) ? '' : date('Y-m-d H:i:s',$item['agenttime']);
            }elseif ($item['status'] == 2){ //平台已充值 待商家确认
                $item['time'] = empty($item['platformtime']) ? '' : date('Y-m-d H:i:s',$item['platformtime']);
            }elseif ($item['status'] == 3){ //充值完成
                $item['time'] = empty($item['platformtime']) ? '' : date('Y-m-d H:i:s',$item['platformtime']);
            }
            if (!empty($item['agent_record'])){
                $arr[] = $item['agent_record'];
            }
            if (!empty($item['platform_record'])){
                $arr[] = $item['platform_record'];
            }
            $item['images'] = $arr;
            unset($item['platformtime'],$item['agenttime'],$item['agent_record'],$item['platform_record']);
            return $item;
        });
        return $list;

    }

    /**
     * 商家充值
     * @return mixed
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recharge()
    {
        $shop = model('shop')->find($this->shopId);
        //查看是否有申请未完全走完的申请
        $res = Recharge::where(['shop_id'=>$this->shopId,'status'=>['in',[0,1,2]]])->find();
        if (!empty($res))
            throw new ApiException('您有申请待审核中，请勿重复申请',404);
        if ($shop['fixed_amount'] > 0) {
            Message::create(['agent_id'=>$shop['agent_id'],'content'=>$shop['shop_name'].'发起一笔充值申请']);//发送站内信
            $agent_info = Agent::get($shop['agent_id']);
            if (!empty($agent_info) && !empty($agent_info['member_id'])){
                Queue::push(\app\job\Message::class,[
                    'member_id'=>$agent_info['member_id'],
                    'template_id'=>config('wechat_gzh')['gzh_template']['daichuligongdan'],
                    'data'=>[
                        'thing41'=>"请处理商家发起的充值申请",
                        'thing14'=>$shop['shop_name'],
                        'time15'=>date('Y-m-d H:i'),
                        'short_thing5'=>"待处理"
                    ]
                ],'message');
            }


            return $this->model->save([
                'shop_id'  => $this->shopId,
                'money'    => $shop['fixed_amount'],
                'agent_id' => $shop['agent_id'],
                'status'   => Recharge::STATUS_AGENT_RECHARGE,
            ]);
        } else {
            throw new ApiException('充值金额未设定',404);
        }
    }

    /**
     * 确认充值
     * @param array $params
     * @return MoneyRecord
     * @throws ApiException
     * @throws \think\exception\DbException
     */
    public function confirm(array $params)
    {
        Db::startTrans();
        try{
            $recharge = Recharge::get(['id' => $params['id'], 'shop_id' => MemberVo::instance()->getShopId()]);
            if (!$recharge)
                throw new ApiException('充值订单不存在',404);
            if ($recharge['status'] !== Recharge::STATUS_CONFIRM) {
                throw new ApiException('充值订单状态异常',404);
            }
            // 修改充值订单状态
            $recharge->status = Recharge::STATUS_COMPLETE;
            $recharge->save();
            // 增加商家余额
            $shop = Shop::getShopForLock($this->shopId);
            if (empty($shop))
                throw new ApiException('商家状态错误',404);
            $shop->money = bcadd($shop->money, $recharge['money'], 2);
            $shop->save();
            // 写入充值记录
            MoneyRecord::shopRecharge($recharge, $shop);
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage(),404);
        }

    }

}